# -*- coding: utf-8 -*-
from case_util.interface_test import config_parser
import json
from pymysql.pymysql import DB
import MySQLdb
import logging


class CaseCoreInterface:
    def add_case(self, case_no, project_id, product_id, title, case_type):
        isok = DB('db0').Table('product').Insert(
            {'case_no': case_no, 'title': title, 'project_id': project_id, 'product_id': product_id,
             'case_type': case_type})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def get_case_list(self, product_id, project_id, title, case_type, test_status):
        flag = False
        colnum = ''
        args = []
        if product_id:
            colnum = colnum + 'product_id=?'
            args.append(product_id)
            flag = True
        if project_id and flag:
            colnum = colnum + 'and project_id=?'
            args.append(project_id)
            flag = True
        elif project_id:
            colnum = colnum + 'project_id=?'
            args.append(project_id)
            flag = True
        if title and flag:
            colnum = colnum + 'and title =?'
            args.append(title)
            flag = True
        elif title:
            colnum = colnum + 'title=?'
            args.append(product_id)
            flag = True
        if case_type and flag:
            colnum = colnum + 'and case_type =?'
            args.append(case_type)
            flag = True
        elif case_type:
            colnum = colnum + 'case_type=?'
            args.append(case_type)
            flag = True
        if test_status and flag:
            colnum = colnum + 'and test_status =?'
            args.append(test_status)
            flag = True
        elif test_status:
            colnum = colnum + 'test_status=?'
            args.append(test_status)
            flag = True
        if flag:
            sql = " DB('db0').Select('p.name project_name,c.id,c.case_no,c.title,c.case_type,c.test_status').From('cases c').Join('project p','p.id=c.project_id').Where(%s,%s).GetAll()" % (
                "'" + colnum + "'", str(args))
        else:
            sql = " DB('db0').Select('p.name project_name,c.id,c.case_no,c.title,c.case_type,c.test_status').From('cases c').Join('project p','p.id=c.project_id').GetAll()"

        case_list = eval(sql)
        if case_list:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': case_list})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def get_case_by_id(self, case_id):
        case = DB('db0').Select('p.name project_name,c.case_no,c.title,c.case_type,c.test_status').From('cases c').Join(
            'project p', 'p.id=c.project_id').Where('c.id=?', [case_id]).GetAll()
        steps = DB('db0').Select('id,step_type,data_from,expression,description').From('steps').Where('case_id=?',
                                                                                                      [
                                                                                                          case_id]).GetAll()
        step_list = []
        for i in steps:
            req_args = DB('db0').Select('name,content').From('req_args').Where('step_id=?', [i['id']]).GetAll()
            checks = DB('db0').Select('check_type,query_sql,check_rule').From('checks').Where('step_id=?',
                                                                                              [i['id']]).GetAll()
            step_list.append({'step': i, 'req_args': req_args, 'checks': checks})
        if case:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps(
                {'code': cm['code'], 'message': cm['message'], 'data': {'case': case, 'steps': step_list}})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def update_case_status_by_id(self, case_id, status):
        data = {'status': status}
        isok = DB('db0').Table('cases').Where('id=?', [case_id]).Update(data)
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def execute_case(self, case_id):
        pass

    def add_step(self, case_id, step_type, en_alias, process_mode, expression, description, step_index, args_list,
                 check_list):
        DB('db0').Begin()
        step_id = ''
        step_isok = DB('db0').Table('steps').Insert(
            {'case_id': case_id, 'step_type': step_type, 'en_alias': en_alias, 'process_mode': process_mode,
             'expression': expression, 'description': description, 'step_index': step_index})
        if step_isok:
            step_id = DB('db0').GetLastInsertId()
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        if expression == 'REQUEST_API':
            if type(args_list) == type([]):
                data = []
                for i in args_list:
                    i['step_id'] = step_id
                    data.append(i)
                args_isok = DB('db0').Table('req_args').Insert(data)
            if not args_isok:
                DB('db0').End(False)
                cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
                return json.dumps({'code': cm['code'], 'message': cm['message']})
            if type(check_list) == type([]):
                data = []
                for i in check_list:
                    i['step_id'] = step_id
                    data.append(i)
                check_isok = DB('db0').Table('req_args').Insert(data)
            if not check_isok:
                DB('db0').End(False)
                cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
                return json.dumps({'code': cm['code'], 'message': cm['message']})

    def get_step_by_id(self, step_id):
        step = DB('db0').Select('*').From('steps').GetAll()
        req_args = DB('db0').Select('*').From('steps').Where('step_id=?', [step_id]).GetAll()
        checks = DB('db0').Select('*').From('checks').Where('step_id=?', [step_id]).GetAll()
        if step:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message'],
                               'data': {'step': step, 'req_args': req_args, 'checks': checks}})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def remove_step_for_case(self, step_id, status):
        isok = DB('db0').Table('step').Where('id=?', [step_id]).Update({'status': status})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def add_data_source(self, k, v, make_from):
        isok = DB('db0').Table('data_source').Insert({'k': k, 'v': v, 'make_from': make_from})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def get_data_source(self, data_source_id=None, k=None):
        data_source = ''
        if data_source_id:
            data_source = DB('db0').Select('k,v,make_from').From('data_source').Where('id=?', [data_source_id]).GetAll()
        elif k:
            data_source = DB('db0').Select('id,k,v,make_from,status').From('data_source').Where('k=?', [k]).GetAll()
        else:
            data_source = DB('db0').Select('id,k,v,make_from,status').From('data_source').GetAll()

        if data_source:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': data_source})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def update_data_source_status_by_id(self, data_source_id, status):
        data = {'status': status}
        isok = DB('db0').Table('data_source').Where('id=?', [data_source_id]).Update(data)
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
